package jp.co.neosystem.s2wg.service.flex.impl;

import java.sql.Date;
import java.util.List;

import jp.co.neosystem.s2wg.dto.flex.ArgsUpdateWorkSheet;
import jp.co.neosystem.s2wg.dto.flex.ResultUpdateWorkSheet;
import jp.co.neosystem.s2wg.entity.TblTrnWorktime;
import jp.co.neosystem.s2wg.service.dao.WorktimeDetailService;
import jp.co.neosystem.s2wg.service.dao.WorktimeService;
import jp.co.neosystem.s2wg.service.flex.UpdateWorkSheetService;
import jp.co.neosystem.s2wg.util.DateUtil;
import jp.co.neosystem.s2wg.util.MessageCode;
import jp.co.neosystem.s2wg.util.StatusFactory;

import org.seasar.flex2.rpc.remoting.service.annotation.RemotingService;
import org.seasar.framework.beans.util.BeanMap;

/**
 * ワークシート更新サービスクラス。
 */
@RemotingService
public class UpdateWorkSheetServiceImpl implements UpdateWorkSheetService {

	public WorktimeService worktimeService;

	public WorktimeDetailService worktimeDetailService;

	@Override
	public ResultUpdateWorkSheet updateWorkSheet(
			final ArgsUpdateWorkSheet args, final boolean isTest) {
		final ResultUpdateWorkSheet ret = new ResultUpdateWorkSheet();

		// DBデータの取得
		final BeanMap condition = new BeanMap();
		condition.put("userId", args.getUserId());
		condition.put("targetYearMonth", DateUtil.format(args
				.getWorksheetList().get(0).getBaseDate(), "yyyyMM"));

		final List<TblTrnWorktime> w = worktimeService
				.findByCondition(condition);

		if (w == null || w.size() != 1) {
			ret.setStatus(StatusFactory
					.getStatus(MessageCode.WORKSHEET_UPDATE_NG));
			return ret;
		}

		condition.clear();
		condition.put("workId", w.get(0).workId);

		// DB更新
		w.get(0).updateDate = new Date(System.currentTimeMillis());
		worktimeService.update(w.get(0));
		worktimeDetailService.updateBatch(w.get(0).workId,
				args.getWorksheetList());

		ret.setStatus(StatusFactory.getStatus(MessageCode.WORKSHEET_UPDATE_OK));
		return ret;
	}

}
